import { ComponentProps, Computed, Hook, Mut, VueComponent } from "vue3-oop"
import { FormItem, TimePicker } from 'ant-design-vue';
import { WidgetNode } from '../../types'
import { parseDayjs,dayjs } from "@/utils/DayjsUtil";
import { TIMEPICKER } from "./attr-timepicker";

interface IProps {
  widgetNode: WidgetNode
}
export default class FvrTimepicker extends VueComponent<IProps> {
  static defaultProps: ComponentProps<IProps> = {
    widgetNode: {}
  }

  constructor(
  ) {
    super();
  }

  @Mut() state = {
    value: ''
  }

  @Computed() get cmpValue(){
    return this.state.value.length>0?dayjs(this.state.value,'HH:mm:ss'):undefined;
  }

  setValue = ():void=>{
    const { widgetNode } = this.props;
    const { widgetItem } = widgetNode;
    const attr = widgetItem[widgetItem.type] as TIMEPICKER;
    attr.field_value = this.state.value as string;
  }
  
  loadValue = ():void=>{
    const { widgetNode } = this.props;
    const { widgetItem } = widgetNode;
    const attr = widgetItem[widgetItem.type] as TIMEPICKER;
    this.state.value = attr.field_value;
  }

  onValueChange=(value:string|dayjs.Dayjs|null,dateString:string)=>{
    this.state.value = dateString;
    // 有 blur 事件，失去焦点才触发更新 widgetItem 的 field_value
    // this.setValue();
  }

  @Hook('Mounted')
  onMounted(){
    const { widgetNode } = this.props;
    const { widgetItem } = widgetNode;
    const attr = widgetItem[widgetItem.type] as TIMEPICKER;

    widgetItem.setValue = this.setValue;
    widgetItem.loadValue = this.loadValue;
    
    if(!attr.field_value||attr.field_value===''){
      attr.field_value = attr.field_default;
    }
    this.state.value = attr.field_value;
  }

  render() {
    const { widgetNode } = this.props;
    const { widgetItem } = widgetNode;
    const attr = widgetItem[widgetItem.type] as TIMEPICKER;

    const labelAlign = attr.formitem_labelAlign;
    const labelCol = { style: { width: `${attr.formitem_labelWidth}px` } }
    const isRequired = attr.layout_status==='4'

    const rules = [];
    if(isRequired){
      rules.push({ required: true, message: `请选择[${attr.field_label}]` })
    }

    return (
      <FormItem
        name={attr.field_code} 
        labelCol={labelCol} 
        labelAlign={labelAlign} 
        label={attr.field_label} 
        rules={rules}
      >
        <TimePicker 
          style={{width:'100%'}}
          defaultValue={this.cmpValue}
          value={this.cmpValue}
          onChange={this.onValueChange} 
          onBlur={this.setValue}
        />
      </FormItem>
    )
  }
}